<script setup lang="ts">
import { ref } from 'vue';
import { Progress as AProgress } from '@arco-design/web-vue';

// 定义组件暴露的方法类型
export interface LoadingBarInstance {
  start: () => number;
  finish: (success?: boolean) => Promise<boolean>;
  reset: () => void;
}

// 进度值
const percent = ref(0);
// 加载状态
const status = ref<'normal' | 'success' | 'error'>('normal');

// 重置加载条
const reset = () => {
  percent.value = 0;
  status.value = 'normal';
};

// 开始加载动画
const start = (): number => {
  reset();
  const timer = window.setInterval(() => {
    percent.value += Math.random() * 10;
    if (percent.value > 90) {
      clearInterval(timer);
    }
  }, 200);
  return timer;
};

// 结束加载动画
const finish = (success = true): Promise<boolean> => {
  return new Promise(resolve => {
    percent.value = 100;
    status.value = success ? 'success' : 'error';
    setTimeout(() => {
      reset();
      resolve(true);
    }, 100);
  });
};

// 暴露方法
defineExpose<LoadingBarInstance>({
  start,
  finish,
  reset
});
</script>

<template>
  <div
      class="loading-bar-container"
      :style="{ top: '-13px', left: '0', width: '100%', position: 'fixed', zIndex: '10000' }"
  >
    <a-progress
        :percent="percent"
        :stroke-width="5"
        status="success"
        :show-text="false"
    />
  </div>
</template>

<style scoped>

</style>
